package cat.widget.acgmoe.acgmoewidget.Utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;

import cat.widget.acgmoe.acgmoewidget.R;
import cat.widget.acgmoe.acgmoewidget.Server.MyApplication;
import cat.widget.acgmoe.acgmoewidget.Utils.IoUtils.FileHelper;
import cat.widget.acgmoe.acgmoewidget.Utils.IoUtils.FileNameHelper;

/**
 * Created by cat on 2018/4/27.
 */

public class NewImgAdapter extends BaseAdapter {
    /**
     * 缓存的所有图片列表
     */
    public static String[] TempImgInfoList = new FileHelper().GetAssetsList(MyApplication.getContext(), "custom_img");

    @Override
    public int getCount() {
        if (TempImgInfoList != null)
            return TempImgInfoList.length;
        else
            return 0;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    /**
     * @param i
     * @param view
     * @param viewGroup
     * @return
     */
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {

        View Tempview = null;

        //获取填充器对象，这个对象可以帮助我们绘制出items项，获取方式有多种：


        String GetImgInfo = TempImgInfoList[i];//通过回调这个方法传过来的position参数获取到指定数据源中的对象
        //找到布局文件中的控件

        LayoutInflater inflater = (LayoutInflater) MyApplication.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Tempview = inflater.inflate(R.layout.griditem_addpic, null);
        ImageView singleimg = Tempview.findViewById(R.id.singleimg);
        TextView ImgFileName = Tempview.findViewById(R.id.ImgFileName);
        ImgFileName.setText(FileNameHelper.GetFileNameWithoutExtension(GetImgInfo));
        Bitmap TempBitmap = GetBitMap(GetImgInfo);
        if (TempBitmap != null)
            singleimg.setImageBitmap(TempBitmap);
        else
            PrintLog.Log("读取图像失败");

        return Tempview;
    }

    /**
     * @param i
     * @return
     */
    public Bitmap GetBitMap(int i) {
        String GetImgInfo = TempImgInfoList[i];//通过回调这个方法传过来的position参数获取到指定数据源中的对象
        return GetBitMap(GetImgInfo);
    }

    private Bitmap GetBitMap(String getImgInfo) {

        try {
            String temp = "custom_img/" + getImgInfo;
            InputStream open = MyApplication.getContext().getAssets().open(temp);
            return BitmapFactory.decodeStream(open);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}
